package com.xiaoqi.store.controller;


import com.xiaoqi.store.entity.JsonResult;
import com.xiaoqi.store.entity.UserEntity;
import com.xiaoqi.store.exception.impl.FileEmptyException;
import com.xiaoqi.store.exception.impl.FileSizeException;
import com.xiaoqi.store.exception.impl.FileTypeException;
import com.xiaoqi.store.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author Rookie Coder
 * @Description 用户控制层
 * @Date
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    /**
     * 头像文件大小的上限值(10MB)
     */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    /**
     * 允许上传的头像的文件类型
     */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    @Autowired
    private UserService userService;

    /*
     * @Author xiaoqi
     * @Description  ajax-检查用户名是否重复
     * @return true 或 false
     **/
      /*@RequestMapping("/checkUserName")
        @ResponseBody
        public Boolean checkUserName(String username){
            boolean b = userService.checkUserName(username);
            log.info("是否可用+ "+b);
            return b;
        }*/

    /*
     * @Author xiaoqi
     * @Description  用户注册
     * @return
     **/
    @RequestMapping("/registUser")
    public JsonResult<Void> registerUser(UserEntity userEntity, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        userService.regUser(userEntity);
        // 注册成功
        return new JsonResult<Void>(OK);
    }

    /*
     * @Author xiaoqi
     * @Description  用户登录
     * @return true 或 false
     **/
    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult<UserEntity> userLogin(HttpSession session, String username, String password) {
        UserEntity userEntity = userService.userLogin(username, password);
        JsonResult<UserEntity> jsonResult = new JsonResult<>();
        // 登录成功。转到首页，并且保存用户信息进session中
        if (userEntity != null) {
            session.setAttribute("uid", userEntity.getUId());
            session.setAttribute("username", userEntity.getUsername());
            log.info("登录成功，用户信息为: " + userEntity);
            jsonResult.setState(200);
            jsonResult.setMessage("登录成功");
            jsonResult.setData(userEntity);
            return jsonResult;
        }
        // 登录失败
        else {
            log.info("登录失败");
            jsonResult.setState(699);
            jsonResult.setMessage("登录失败");
            return jsonResult;
        }
    }

    /*
     * @Author xiaoqi
     * @Description  修改密码
     * @return true  false
     **/
    @RequestMapping("/updateUserPassword")
    public JsonResult<Void> updateUserPassword(String oldPassword, String newPassword, HttpSession session) {
        // 从session中获取用户名和uid
        Integer uidFromSession = getUidFromSession(session);
        String usernameFromSession = getUsernameFromSession(session);
        log.info("原密码 " + oldPassword);
        log.info("新密码 " + newPassword);
        // 调用service层业务代码
        userService.updateUserPassword(uidFromSession, usernameFromSession, oldPassword, newPassword);
        return new JsonResult<Void>(OK);
    }

    /*
     * @Author xiaoqi
     * @Description  ajax-查询用户信息
     * @return
     **/
    @GetMapping("/selectUserByUid")
    public JsonResult<UserEntity> selectUserByUid(HttpSession session) {
        // 获取到session的值
        Integer uidFromSession = getUidFromSession(session);
        UserEntity userEntity = userService.selectUserByUid(uidFromSession);
        JsonResult<UserEntity> jsonResult = new JsonResult<>();
        jsonResult.setState(OK);
        jsonResult.setData(userEntity);
        return jsonResult;
    }

    /*
     * @Author xiaoqi
     * @Description  修改用户信息
     * @return
     **/
    @PostMapping("/changeUserInfo")
    public JsonResult<Void> changeUserInfo(Integer gender, String phone, String email, HttpSession session) {
        String usernameFromSession = getUsernameFromSession(session);
        //      log.info("传过来的username信息 "+username);
        userService.changeUserInfo(gender, usernameFromSession, phone, email);
        return new JsonResult<>(OK);
    }

    /*
     * @Author xiaoqi
     * @Description  用户图像上传
     * @return
     **/
    @PostMapping("/changeUserAvatar")
    public JsonResult<String> changeUserAvatar(@Param("file") MultipartFile file, HttpSession session) {

        // 判断上传的文件是否为空
        if (file == null && file.getSize() == 0) {
            // 是：抛出异常
            log.info("文件为空");
            throw new FileEmptyException("文件为空");
        }
        // 判断上传的文件大小是否超出限制值
        // 是：抛出异常
        if (file.getSize() > AVATAR_MAX_SIZE) {
            log.info("不允许超过" + AVATAR_MAX_SIZE / 1024 + "字节的图片");
            throw new FileSizeException("不允许超过" + AVATAR_MAX_SIZE / 1024 + "字节的图片");
        }
        // 判断上传的文件类型是否超出限制
        // 是：抛出异常
        if (!AVATAR_TYPES.contains(file.getContentType())) {
            log.info("不允许使用该类型的文件");
            throw new FileTypeException("不允许使用该类型的文件");
        }
        // 获取当前项目的绝对磁盘路径
        String upload = session.getServletContext().getRealPath("upload");
        log.info("当前项目磁盘路径: " + session.getServletContext().getContextPath());
        log.info("当前文件夹的绝对路径： " + upload);
        // 保存头像文件的文件夹
        File saveUserAvatar = new File(upload);
        // 如果改文件夹不存在
        if (!saveUserAvatar.exists()) {
            // 创建
            saveUserAvatar.mkdir();
        }

        // 保存的头像文件的文件名
        String suffix = "";
        // 获取到上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        log.info("上传文件的文件名： " + originalFilename);
        // 返回
        int i = originalFilename.lastIndexOf(".");
        if (i > 0) {
            suffix = originalFilename.substring(i);
        }
        log.info("上传文件的后缀： " + suffix);
        // 新生成的文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        log.info("新生成的文件名: " + fileName);
        // 执行保存头像文件
        File newFile = new File(saveUserAvatar, fileName);

        // 如果产生异常则抛出
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 头像路径
        String avatar = "/upload/" + fileName;
        log.info("图像路径 " + avatar);
        // 从Session中获取uid和username
        Integer uidFromSession = getUidFromSession(session);
        String usernameFromSession = getUsernameFromSession(session);
        // 将头像写入到数据库中
        userService.uploadUserAvator(uidFromSession, avatar);
        log.info("图像更新完成");
        // 返回成功和头像路径
        return new JsonResult<String>(OK, avatar);
    }

}
